//引入mysql模块
var mysql = require("mysql");
//创建并设置数据库连接
var conn = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "itcast"
});
//打开连接
conn.connect();
//查询所有数据
module.exports.getAllData = function (callback) {
    var sql = "SELECT * FROM heros WHERE isDel = 0";
    conn.query(sql, (err, results, fields) => {
        if (err) {
            callback(err);
        }
        else {
            callback(null, results);
        }
    })
}
//新增数据
module.exports.insertData = function (newObj, callback) {
    var sql = `INSERT INTO heros(name,gender,img) VALUES('${newObj.name}','${newObj.gender}','${newObj.img}')`;
    conn.query(sql, (err, results, fields) => {
        if (err) {
            callback(err);
        }
        else {
            callback(null, results.affectedRows);
        }
    })
}
//查询单条数据
module.exports.queryDataById = function (id, callback) {
    var sql = `SELECT * FROM heros WHERE isDel = 0 AND ID = ${id}`;
    conn.query(sql, (err, results, fields) => {
        if (err) {
            callback(err);
        }
        else {
            callback(null, results[0]);
        }
    })
}
//更新数据
module.exports.updateDataById = function (newObj, callback) {
    var sql = `UPDATE heros SET name='${newObj.name}',gender='${newObj.gender}',img='${newObj.img}' WHERE isDel = 0 AND ID = ${newObj.id}`;
    conn.query(sql, (err, results, fields) => {
        if (err) {
            callback(err);
        }
        else {
            callback(null, results.affectedRows);
        }
    })
}
//删除数据
module.exports.delDataById = function (id, callback) {
    var sql = `UPDATE heros SET isDel = 1 WHERE ID = ${id}`;
    conn.query(sql, (err, results, fields) => {
        if (err) {
            callback(err);
        }
        else {
            callback(null, results.affectedRows);
        }
    })
}